package com.ht.sps.nh.module;


import com.ht.sps.nh.entity.TreeMenu;
import com.ht.sps.nh.service.TemplateSettingService;
import com.ht.sps.nh.service.impl.TemplateSettingServiceImpl;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.View;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.upload.FieldMeta;
import org.nutz.mvc.upload.TempFile;
import org.nutz.mvc.upload.UploadAdaptor;
import org.nutz.mvc.view.ThymeleafView;
import org.nutz.mvc.view.ThymeleafViewMaker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@IocBean
@At("/nh/template/template_setting")
public class TemplateSettingModule {
    private static final Logger log = LoggerFactory.getLogger(TemplateSettingModule.class);

    //设置图片上传路径
    private static final String RING_PATH = "/resources/img/template";

    //设置上传文件路径
    private static final String UPLOAD_PATH = Mvcs.getServletContext().getRealPath(RING_PATH);

    private static final String IMG_PATH = "../../../../resources/img/template/";

    @Inject
    private TemplateSettingService templateSettingService;

    @At("/")
    //@Ok("th:nh/template/template_setting")
    public View index(HttpServletRequest request,@Param("nodeId") int nodeId,@Param("modelCount") int modelCount) {
        log.info("进入到模板设置功能，树节点Id为{}",nodeId);
        ThymeleafView view = null;
        request.setAttribute("nodeId",nodeId);
        TreeMenu treeMenu = findNodeInforByNodeId(nodeId);
        if(modelCount==0){//只做显示
            request.setAttribute("type","show");
            if(treeMenu!=null){
                request.setAttribute("modelCount",treeMenu.getModelCount());
                modelCount = treeMenu.getModelCount();//做显示时，要找到真正的modelCount用于下面的判断。
            }
        }else{//模板设置
            request.setAttribute("type","set");
            request.setAttribute("modelCount",modelCount);
        }
//        request.setAttribute("url1",formatLinkUrl(treeMenu.getModelUrl1()));
//        request.setAttribute("url2",formatLinkUrl(treeMenu.getModelUrl2()));
//        request.setAttribute("url3",formatLinkUrl(treeMenu.getModelUrl3()));
//        request.setAttribute("url4",formatLinkUrl(treeMenu.getModelUrl4()));
//        request.setAttribute("url5",formatLinkUrl(treeMenu.getModelUrl5()));
        switch (modelCount){
            case 1:
                view =  new ThymeleafView(ThymeleafViewMaker.templateEngine, "nh/template/template1");
                break;
            case 2:
                view =  new ThymeleafView(ThymeleafViewMaker.templateEngine, "nh/template/template2");
                break;
            case 3:
                view =  new ThymeleafView(ThymeleafViewMaker.templateEngine, "nh/template/template3");
                break;
            case 5:
                view =  new ThymeleafView(ThymeleafViewMaker.templateEngine, "nh/template/template5");
                break;
        }
        return view;
    }

    /**
     * 保存链接到数据库
     * @param nodeId 树节点Id
     * @param number 模板第几部分
     * @param linkName 链接
     * @param titleName 标题名称
     * @param autoFit 窗口自适应属性
     */
    @At
    @Ok("fastjson")
    public void saveLinkName(@Param("nodeId") int nodeId,@Param("number") int number,@Param("linkName") String linkName,@Param("titleName") String titleName,@Param("autoFit") String autoFit){
        templateSettingService.saveImageName(linkName,titleName,nodeId,number,autoFit);
    }

    /**
     * 根据节点Id查找节点信息
     * @param nodeId
     * @return
     */
    @At
    @Ok("fastjson")
    public TreeMenu findNodeInforByNodeId(@Param("nodeId") int nodeId){
        return templateSettingService.findNodeInforByNodeId(nodeId);
    }

    /**
     * 修改所属模板
     * @param nodeId 树节点Id
     * @param modelCount 模板编号
     */
    @At
    @Ok("fastjson")
    public void updateModelCount(@Param("nodeId") int nodeId,@Param("modelCount") int modelCount){
        templateSettingService.updateModelCount(nodeId,modelCount);
    }

    /**
     * 获取url
     * @param nodeId
     */
    @At
    @Ok("fastjson")
    public List getUrl(@Param("nodeId") int nodeId) {
        TreeMenu treeMenu = findNodeInforByNodeId(nodeId);
        List urls = new ArrayList();
        if(treeMenu!=null){
            urls.add(0,formatLinkUrl(treeMenu.getModelUrl1(),treeMenu.getTitle1()));
            urls.add(1,formatLinkUrl(treeMenu.getModelUrl2(),treeMenu.getTitle2()));
            urls.add(2,formatLinkUrl(treeMenu.getModelUrl3(),treeMenu.getTitle3()));
            urls.add(3,formatLinkUrl(treeMenu.getModelUrl4(),treeMenu.getTitle4()));
            urls.add(4,formatLinkUrl(treeMenu.getModelUrl5(),treeMenu.getTitle5()));
        }
        return urls;
    }

    /**
     * 只做修改iframe窗口类型
     * @param nodeId 树节点Id
     * @param titleName 标题名称
     * @param number 模板第几部分
     * @param autoFit 窗口自适应属性
     */
    @At
    @Ok("fastjson")
    public String updateIframeType(@Param("nodeId") int nodeId,@Param("titleName") String titleName,@Param("number") int number,@Param("autoFit") String autoFit){
        return templateSettingService.updateIframeType(nodeId,titleName,number,autoFit);
    }

    /**
     * 图片文件上传
     * @param request
     * @param file 流文件
     * @param nodeId 树节点Id
     * @param number 模板第几部分
     * @param titleName 标题名称
     * @param autoFit 窗口自适应属性
     * @return
     */
    @At
    @Ok("fastjson")
    @AdaptBy(type = UploadAdaptor.class,args={"${app.root}/WEB-INF/temp"})
    public Map<String,String> upload(HttpServletRequest request,@Param("imgName")TempFile file,@Param("nodeId") int nodeId,@Param("number") int number,@Param("titleName") String titleName,@Param("autoFit") String autoFit){
        String upload_path = request.getServletContext().getRealPath("/resources/img/template");
        Map<String,String> resMap = new HashMap<String,String>();
        BufferedInputStream fileIn = null;
        BufferedOutputStream fileOut = null;
        File f = file.getFile();//保存的临时文件
        log.debug("..................."+f.length());
        FieldMeta meta = file.getMeta();
        String fileName = meta.getFileLocalName().replaceAll(" ","");
        try {
            fileIn = new BufferedInputStream(new FileInputStream(f));
            File tempFile = new File(upload_path);
            if(!tempFile.exists()){
                tempFile.mkdirs();
            }
            log.debug("......................"+upload_path);
            deleteFile(new File(upload_path),fileName);
            byte[] buf = new byte[1024];
            fileOut = new BufferedOutputStream(new FileOutputStream(new File(upload_path+"/"+fileName)));
            while (true) {
                // 读取数据
                int bytesIn = fileIn.read(buf, 0, 1024);
                if (bytesIn == -1){
                    break;
                }else{
                    fileOut.write(buf, 0, bytesIn);
                    fileOut.flush();
                }
            }
            fileOut.close();
            templateSettingService.saveImageName(IMG_PATH+fileName,titleName,nodeId,number,autoFit);
            resMap.put("src",IMG_PATH+fileName);
        }catch(Exception e){
            resMap.put("src","");
            e.printStackTrace();
            log.debug("upload template image error");
        }finally {
            try {
                fileOut.close();
                fileIn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resMap;
    }

    /**
     * 删除某个文件
     */
    public void deleteFile(File file,String fileName){
        if(file.isDirectory()){
            File[] files = file.listFiles();
            for(File f:files){
                deleteFile(f,fileName);
            }
        }else{
            String  name = file.getName();
            if(name.equals(fileName)){
                file.delete();
            }
        }
    }

    public String[] formatLinkUrl(String url,String titleName){
        String urlT = url.toLowerCase();
        String[] res = new String[3];
        if(urlT.indexOf("https://")>=0||urlT.indexOf("http://")>=0){
            int endIndex = url.indexOf("|");
            res[0] = url.substring(0,endIndex);
            res[1] = url.substring(endIndex+1);
        }else{
            if(urlT.indexOf("../../../../")>=0){
                int beingIndex = url.lastIndexOf("/");
                int endIndex = url.indexOf("|");
                res[0] = url.substring(beingIndex+1,endIndex);
                res[1] = url.substring(endIndex+1);
            }else{
                res[0] = "";
                res[1] = "";
            }
        }
        res[2] = titleName;
        return res;
    }
}
